package com.meiyu.live.tv.widget;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.chatroom.ChatRoomService;
import com.netease.nimlib.sdk.chatroom.constant.MemberQueryType;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMember;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.meiyu.live.BaseActivity;
import com.meiyu.live.R;
import com.meiyu.live.eventbus.FocusEvent;
import com.meiyu.live.net.param.IsfocusParams;
import com.meiyu.live.net.response.BaseResponse;
import com.meiyu.live.ui.main.GetGiftsActivity;
import com.meiyu.live.util.ToastUtil;
import com.meiyu.live.widget.UserInfoDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * 直播的视频播放界面头部view
 * Created by zbl on 2016/8/12.
 */
public class TvTitleView extends FrameLayout implements View.OnClickListener {

    public final static int MAX_SHOW_MEMBERS = Integer.MAX_VALUE;

    private Context context;
    private ImageLoader imageLoader;
    private DisplayImageOptions options;
    private OnTvTitleViewClickListener listener;
    private UserInfoDialog userInfoDialog;

    private RecyclerView recyclerView;
    private LinearLayoutManager layoutManager;
    private AudienceAdapter adapter;
    private List<ChatRoomMember> memberList = new ArrayList<>();

    private TextView tv_name, tv_membercount, btn_follow, tv_coins, tv_account;
    private ImageView iv_avatar;
    private View btn_back;
    private View layout_money, btn_manage;

    private long anchorId;
    private long roomId;
    private boolean isFollow;
    private boolean isGetData = true;

    private boolean isShowFollowButton = false;
    private String neteaseId;

    public interface OnTvTitleViewClickListener {
        void onBack();

        void onClickPrivateMessage(String neteaseId);

        void onClickManage();
    }

    public TvTitleView(Context context) {
        super(context);
        init(context);
    }

    public TvTitleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        this.context = context;
        imageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.icon_def_header)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.icon_def_header)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.icon_def_header)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
                .build();
        LayoutInflater inflater = LayoutInflater.from(context);
        inflater.inflate(R.layout.view_tvtitle, this);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview_audience);
        layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        adapter = new AudienceAdapter();
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);

        btn_back = findViewById(R.id.btn_back);
        btn_back.setOnClickListener(this);
        tv_name = (TextView) findViewById(R.id.tv_name);
        iv_avatar = (ImageView) findViewById(R.id.iv_avatar);
        iv_avatar.setOnClickListener(this);
        tv_membercount = (TextView) findViewById(R.id.tv_membercount);
        tv_coins = (TextView) findViewById(R.id.tv_coins);
        layout_money = findViewById(R.id.layout_money);
        layout_money.setOnClickListener(this);
        tv_account = (TextView) findViewById(R.id.tv_account);
        btn_follow = (TextView) findViewById(R.id.btn_follow);
        btn_follow.setOnClickListener(this);
        btn_manage = findViewById(R.id.btn_manage);
        btn_manage.setOnClickListener(this);
        setIsFollow(true);
    }

    public void setOnTvTitleViewListener(OnTvTitleViewClickListener listener) {
        this.listener = listener;
    }

    private OnClickListener onItemClickListener = new OnClickListener() {
        @Override
        public void onClick(View view) {
            int position = (int) view.getTag();
            ChatRoomMember member = memberList.get(position);
            Map<String, Object> map = member.getExtension();
            if (map != null) {
                String netease_id = (String) map.get("net_ease_id");
                userInfoDialog = new UserInfoDialog(context);
                userInfoDialog.setUserId(null, netease_id);
                userInfoDialog.show();
            }
        }
    };


    private class AudienceHolder extends RecyclerView.ViewHolder {
        ImageView iv_avatar;

        public AudienceHolder(View itemView) {
            super(itemView);
            iv_avatar = (ImageView) itemView.findViewById(R.id.iv_avatar);
            iv_avatar.setOnClickListener(onItemClickListener);
        }
    }

    private class AudienceAdapter extends RecyclerView.Adapter<AudienceHolder> {

        LayoutInflater inflater = LayoutInflater.from(context);

        @Override
        public AudienceHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = inflater.inflate(R.layout.adapter_tvtitle_audience, null);
            AudienceHolder holder = new AudienceHolder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(AudienceHolder holder, int position) {
            holder.iv_avatar.setTag(position);
            ChatRoomMember member = memberList.get(position);
            Map<String, Object> map = member.getExtension();
            if (map != null) {
                imageLoader.displayImage((String) map.get("icon"), holder.iv_avatar, options);
            }
        }

        @Override
        public int getItemCount() {
            return memberList.size();
        }
    }

    @Override
    public void onClick(View view) {
        if (view == btn_back) {
            if (listener != null) {
                listener.onBack();
            }
        } else if (view == iv_avatar) {
            userInfoDialog = new UserInfoDialog(context);
            userInfoDialog.setUserId(anchorId + "", neteaseId);
            if (isShowFollowButton) {
                userInfoDialog.setUserInfoListener(new UserInfoDialog.UserInfoListener() {
                    @Override
                    public void onClickFollow() {

                    }

                    @Override
                    public void onClickPrivateMessage(String neteaseId) {
                        if (listener != null) {
                            listener.onClickPrivateMessage(neteaseId);
                            userInfoDialog.dismiss();
                        }
                    }
                });
            }
            userInfoDialog.show();
        } else if (view == btn_follow) {
            if (isGetData) {
                return;
            } else {
                if (isFollow) {//取消关注
                    int a[] = {0, 1};
                    ((BaseActivity) context).request(new IsfocusParams(anchorId, a), BaseResponse.class, new Response.Listener<BaseResponse>() {
                        @Override
                        public void onResponse(BaseResponse onlyStatusResponse) {
                            setIsFollow(false);
                            ToastUtil.show("已取消关注");
                            EventBus.getDefault().post(new FocusEvent(false, anchorId));
                        }
                    });
                } else {//关注
                    int a[] = {1, 1};
                    ((BaseActivity) context).request(new IsfocusParams(anchorId, a), BaseResponse.class, new Response.Listener<BaseResponse>() {
                        @Override
                        public void onResponse(BaseResponse onlyStatusResponse) {
                            setIsFollow(true);
                            ToastUtil.show("关注成功");
                            EventBus.getDefault().post(new FocusEvent(true, anchorId));
                        }
                    });
                }
            }
        } else if (view == btn_manage) {
            if (listener != null) {
                listener.onClickManage();
            }
        } else if (view == layout_money) {
            GetGiftsActivity.start(context, anchorId);
        }
    }

    private int roomMemberDataGet = 0;
    private List<ChatRoomMember> tempMemberList = new ArrayList<>();

    //刷新显示聊天室成员
    public void updateRoomMembers(long room_id) {
        this.roomId = room_id;
        roomMemberDataGet = 0;
        tempMemberList.clear();
        NIMClient.getService(ChatRoomService.class)
                .fetchRoomMembers(roomId + "", MemberQueryType.ONLINE_NORMAL, 0, MAX_SHOW_MEMBERS)
                .setCallback(new RequestCallback<List<ChatRoomMember>>() {
                    @Override
                    public void onSuccess(List<ChatRoomMember> param) {
                        roomMemberDataGet++;
                        tempMemberList.addAll(param);
                        if (roomMemberDataGet == 2) {
                            setMemberList(tempMemberList);
                        }
                    }

                    @Override
                    public void onFailed(int code) {
                        roomMemberDataGet++;
                        if (roomMemberDataGet == 2) {
                            setMemberList(tempMemberList);
                        }
                    }

                    @Override
                    public void onException(Throwable exception) {
                        roomMemberDataGet++;
                        if (roomMemberDataGet == 2) {
                            setMemberList(tempMemberList);
                        }
                    }
                });
        NIMClient.getService(ChatRoomService.class)
                .fetchRoomMembers(roomId + "", MemberQueryType.GUEST, 0, MAX_SHOW_MEMBERS)
                .setCallback(new RequestCallback<List<ChatRoomMember>>() {
                    @Override
                    public void onSuccess(List<ChatRoomMember> param) {
                        roomMemberDataGet++;
                        tempMemberList.addAll(param);
                        if (roomMemberDataGet == 2) {
                            setMemberList(tempMemberList);
                        }
                    }

                    @Override
                    public void onFailed(int code) {
                        roomMemberDataGet++;
                        if (roomMemberDataGet == 2) {
                            setMemberList(tempMemberList);
                        }
                    }

                    @Override
                    public void onException(Throwable exception) {
                        roomMemberDataGet++;
                        if (roomMemberDataGet == 2) {
                            setMemberList(tempMemberList);
                        }
                    }
                });
    }

    private void setMemberList(List<ChatRoomMember> list) {
        if (list != null && list.size() > 0) {
            robotMap.clear();
            memberList.clear();
            for (ChatRoomMember bean : list) {
                Map<String, Object> map = bean.getExtension();
                if (map != null) {
                    if (TextUtils.equals((String) map.get("net_ease_id"), neteaseId)) {
                        Log.e("TvTitleView", "过滤主播本人");
                        continue;//过滤掉主播本人
                    }
                    String ext = (String) map.get("ext");
                    if (!TextUtils.isEmpty(ext)) {//ext不为空，说明是机器人
                        handleRobotMember(bean, ext);
                    }
                }
                memberList.add(bean);
            }
            adapter.notifyDataSetChanged();
            tv_membercount.setText(memberList.size() + "人");
            list.clear();
        }

    }


    private HashMap<String, JSONObject> robotMap = new HashMap<>();

    private void handleRobotMember(ChatRoomMember memberBean, String ext) {//更新机器人map数据
        JSONObject data = robotMap.get(memberBean.getAccount());
        if (data == null) {
            try {
                JSONArray jsonArray = new JSONArray(ext);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject object = jsonArray.getJSONObject(i);
                    String netEaseId = object.optString("net_ease_id");
                    if (!TextUtils.isEmpty(netEaseId)) {
                        robotMap.put(netEaseId, object);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            data = robotMap.get(memberBean.getAccount());
        }
        if (data != null) {
            Map<String, Object> extMap = new HashMap<>();
            extMap.put("net_ease_id", data.opt("net_ease_id"));
            extMap.put("icon", data.opt("icon"));
            extMap.put("level", data.opt("level"));
            extMap.put("nick", data.opt("nick"));
            memberBean.setExtension(extMap);
        }
    }

    public void addMember(long roomId, String neteaseId) {
        if (TextUtils.isEmpty(neteaseId)) {
            return;
        }
        ArrayList<String> accounts = new ArrayList<>();
        accounts.add(neteaseId);
        NIMClient.getService(ChatRoomService.class)
                .fetchRoomMembersByIds(roomId + "", accounts)
                .setCallback(new RequestCallbackWrapper<List<ChatRoomMember>>() {

                    @Override
                    public void onResult(int code, List<ChatRoomMember> result, Throwable exception) {
                        if (result != null && result.size() > 0) {
                            ChatRoomMember member = result.get(0);
                            removeMember(member.getAccount());

                            Map<String, Object> map = member.getExtension();
                            if (map != null) {
                                String ext = (String) map.get("ext");
                                if (!TextUtils.isEmpty(ext)) {//ext不为空，说明是机器人
                                    handleRobotMember(member, ext);
                                }
                            }
                            memberList.add(0, member);
                            adapter.notifyDataSetChanged();
                            tv_membercount.setText(memberList.size() + "人");
                        }
                    }
                });
    }

    public void removeMember(String neteaseId) {
        if (TextUtils.isEmpty(neteaseId)) {
            return;
        }
        for (ChatRoomMember member : memberList) {
            if (TextUtils.equals(member.getAccount(), neteaseId)) {
                memberList.remove(member);
                adapter.notifyDataSetChanged();
                tv_membercount.setText(memberList.size() + "人");
                break;
            }
        }
    }

    public int getMemberCount() {
        return memberList.size();
    }

    public void setAuthorInfo(String author_name, String author_avatar) {
        if (!TextUtils.isEmpty(author_name)) {
            tv_name.setText(author_name);
        }
        imageLoader.displayImage(author_avatar, iv_avatar, options);
    }

    public void setCoins(long coins) {
        tv_coins.setText(coins + "");
    }

    public void setAnchorId(long anchorId) {
        this.anchorId = anchorId;
    }

    public void setCuteCode(String cuteCode) {
        tv_account.setText("账号:" + cuteCode);
    }

    public void setShowFollowButton(boolean isShow) {
        this.isShowFollowButton = isShow;
        btn_follow.setVisibility(isShow ? VISIBLE : GONE);
        btn_manage.setVisibility(!isShow ? VISIBLE : GONE);
    }

    public void setIsFollow(boolean isFollow) {
        isGetData = false;
        this.isFollow = isFollow;
        btn_follow.setText(isFollow ? "已关注" : "关注");
    }

    public boolean getIsFollow() {
        return isFollow;
    }

    public void setNeteaseId(String neteaseId) {
        this.neteaseId = neteaseId;
    }

    public View getLayoutMoney() {
        return layout_money;
    }
}
